package com.cheng.chengrobot;

import com.cheng.chengrobot.domain.Robot;
import com.cheng.chengrobot.domain.RobotFriend;
import com.cheng.chengrobot.domain.RobotGroup;
import com.cheng.chengrobot.handler.gptHandler.FriendGptHandler;
import com.cheng.chengrobot.handler.messageForwardHandler.FriendMessageForwarder;
import com.cheng.chengrobot.handler.gptHandler.GroupGptHandler;
import com.cheng.chengrobot.handler.messageForwardHandler.GroupMessageForwarder;
import com.cheng.chengrobot.service.GroupService;
import com.cheng.chengrobot.service.RobotFriendService;
import com.cheng.chengrobot.service.RobotService;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactory;
import net.mamoe.mirai.auth.BotAuthorization;
import net.mamoe.mirai.event.GlobalEventChannel;
import net.mamoe.mirai.event.events.BotJoinGroupEvent;
import net.mamoe.mirai.event.events.FriendAddEvent;
import net.mamoe.mirai.event.events.FriendMessageEvent;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.SingleMessage;
import net.mamoe.mirai.utils.BotConfiguration;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;
import xyz.cssxsh.mirai.tool.FixProtocolVersion;
import xyz.cssxsh.mirai.tool.KFCFactory;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

@SpringBootApplication
@MapperScan("com.cheng.chengrobot.mappers")
@Component
@Slf4j
public class ChengRobotApplication
{
    private static RobotService robotService = null;
    private static GroupService groupService = null;
    private static RobotFriendService robotFriendService = null;

    static
    {
        FixProtocolVersion.fetch(BotConfiguration.MiraiProtocol.ANDROID_PAD, "8.9.58");
        KFCFactory.install();
    }
    public static void main(String[] args)
            throws IOException, InterruptedException, SQLException
    {

        ConfigurableApplicationContext run = SpringApplication.run(ChengRobotApplication.class, args);
        try
        {
            //获取配置文件
            ConfigurableEnvironment environment = run.getEnvironment();

            //获取service
            robotService = (RobotService) run.getBean(RobotService.class);
            groupService = (GroupService) run.getBean(GroupService.class);
            robotFriendService = (RobotFriendService) run.getBean(RobotFriendService.class);

            //循环登录数据库里面的每一个login=Ture的qq
            for (Robot robot : robotService.getAllRobot())
            {
                System.out.println(robot.getQq());
                //如果不登陆就跳过
                if (!robot.getLogin())
                {
                    continue;
                }
                //修改配置
                BotConfiguration botConfiguration = new BotConfiguration()
                {{
                    //设置登陆协议
                    setProtocol(MiraiProtocol.ANDROID_PAD);

                    //设置缓存与设备信息路径
                    String robotCachePath = environment.getProperty("robot-cache-path");
                    if (!robotCachePath.endsWith(File.separator)) robotCachePath += File.separator;
                    robotCachePath += robot.getCachePath();
                    System.out.println(robotCachePath + File.separator + "cache");
                    System.out.println(robotCachePath + File.separator + "myDeviceInfo.json");

                    //判断是否存在缓存文件夹，不存在则创建
                    File file = new File(robotCachePath);
                    if (!file.exists())
                    {
                        file.mkdirs();
                    }
                    setCacheDir(new File(robotCachePath + File.separator + "cache"));
                    fileBasedDeviceInfo(robotCachePath + File.separator + "myDeviceInfo.json");
                }};
                //登陆
//                Bot bot = BotFactory.INSTANCE.newBot(robot.getQq(), BotAuthorization.byQRCode(), botConfiguration);
                Bot bot = BotFactory.INSTANCE.newBot(robot.getQq(), BotAuthorization.byPassword(robot.getPassword()), botConfiguration);
                //                Bot bot = BotFactory.INSTANCE.newBot(robot.getQq(), robot.getPassword(), botConfiguration);
                bot.login();
            }


            //注册群消息转发器
            GlobalEventChannel.INSTANCE.filter(event -> {
                return event instanceof GroupMessageEvent;
            }).registerListenerHost(run.getBean(GroupMessageForwarder.class));

            //注册好友消息转发器
            GlobalEventChannel.INSTANCE.filter(event -> {
                return event instanceof FriendMessageEvent;
            }).registerListenerHost(run.getBean(FriendMessageForwarder.class));

            //gpt群监听器
            GlobalEventChannel.INSTANCE.filter(event -> {

                return (event instanceof GroupMessageEvent) && isAtMe(((GroupMessageEvent) event));
            }).registerListenerHost(run.getBean(GroupGptHandler.class));

            //gpt好友监听器
            GlobalEventChannel.INSTANCE.filter(event -> {
                return (event instanceof FriendMessageEvent);
            }).registerListenerHost(run.getBean(FriendGptHandler.class));

            //监听好友变动
            GlobalEventChannel.INSTANCE.filter(event -> {
                return event instanceof FriendAddEvent;
            }).subscribeAlways(FriendAddEvent.class, friendAddEvent -> {
                RobotFriend instanceFromFriend = RobotFriend.getInstanceFromFriend(
                        friendAddEvent.getBot().getFriend(friendAddEvent.getFriend().getId()));
                robotFriendService.getMapper().insert(instanceFromFriend);
            });

            //监听群变动
            GlobalEventChannel.INSTANCE.filter(event -> {
                return event instanceof BotJoinGroupEvent;
            }).subscribeAlways(BotJoinGroupEvent.class, botJoinGroupEvent -> {
                RobotGroup instanceFromGroup = RobotGroup.getInstanceFromGroup(botJoinGroupEvent.getGroup());
                groupService.getGroupMapper().insert(instanceFromGroup);
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();

        }
        //刷新数据库里面的群
        groupService.flushGroupListToDB();

        //刷新机器人好友
        robotFriendService.flushRobotFriendsToDB();
    }

    //判断与一个群消息是不是at了机器人
    private static boolean isAtMe(GroupMessageEvent event)
    {

        boolean result = false;

        MessageChain messageChain = event.getMessage();
        for (SingleMessage singleMessage : messageChain)
        {
            if (!(singleMessage instanceof At)) continue;

            At at = (At) singleMessage;
            //如果at的人不是接收到信息的机器人就忽略
            if(at.getTarget() != event.getBot().getId()) continue;

            try
            {
                Bot.getInstance(at.getTarget());
                return true;
            }
            catch (Exception e) {}
        }

        return false;
    }
}
